package com.zw.transition.controller;


import com.zw.transition.base.BaseController;
import com.zw.transition.common.JsonResult;
import com.zw.transition.entity.User;
import com.zw.transition.services.UserService;
import com.zw.transition.util.ServletUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@Controller
public class LoginController extends BaseController {
    @Value("${spring.profiles.active}")
    private String profile;
    @Autowired
    private UserService userService;


    @GetMapping("/")
    public String root(Model model, HttpServletRequest request, HttpServletResponse response) {
        // 如果是Ajax请求，返回Json字符串。
        if (ServletUtils.isAjaxRequest(request)) {
            return ServletUtils.renderString(response, "{\"type\":\"ERROR\",\"msg\":\"未登录或登录超时。请重新登录\"}");
        }
        model.addAttribute("profile", profile);
        return "login";
    }
    /**
     * 登录
     */
    @ResponseBody
    @PostMapping("/login")
    public JsonResult login(User user, HttpSession session) throws IOException {
        User verificationIsFrozen = userService.getTransUserByAccount(user.getAccount());
        if (verificationIsFrozen != null && verificationIsFrozen.getStatus().intValue() == 1) {
            User u = userService.login(user);
            if (u != null) {
                session.setAttribute("user", u);
                return success().setData(u);
            } else {
                return error("帐号密码错误");
            }
        } else if (verificationIsFrozen != null && verificationIsFrozen.getStatus().intValue() == 0) {
            return error("你的账号以锁定，如需解锁请联系ERP管理员。");
        } else {
            return error("帐号密码错误");
        }
    }
    /**
     * 登出
     */
    @ResponseBody
    @PostMapping("/logout")
    public JsonResult logout(User user, HttpSession session) throws IOException {
        session.getAttribute("user");
        session.invalidate();
        return success();
    }
}
